/*
 *Copyright (c) 2014 fengmang studio. All rights reserved
 *
 *build time 2014/6/26 11:25 
 *
 *Edition:1.0
 *
 *Founder:bluekey
 *
 *File name:snake.cpp
 *
 *Description:The realization of the snakes body moving.
 */
#include<curses.h>
#include"head/snake.h"
#include"head/food.h"
#include"head/keyboard.h"
#include"head/screen.h"

int check_max = 50;

int speed = 160;

int score = 0;

void stop_service()
{
	int ch;
	while(true)
	{
		ch = obstruction_read();
		if(ch == stop)
		{
			break;
		}	
	}
}

snake::snake():score(0)
{
	body temp(COLS/2, LINES/2,'*');
	Snake.push_back(temp);
	mvaddch(temp.get_x(), temp.get_y(), get_ch());
	temp.set_y()++;
	Snake.push_back(temp);
	mvaddch(temp.get_x(), temp.get_y(), get_ch());
	application::refresh();
}

bool snake::move_snake()
{
	int flag = 0;
	int Key = up;
	int t_x,t_y;
	
	food Food = new food;

	while (true)
	{
		if (Food->new_food(Snake) == false)
		{
			printw("ERROR!");
			return false;
		}
		if (flag > check_max)
		{
			return true;	//该进入下一关了
			check_max+=10;
			speed-=20;
			if(speed >= 0)
			{
				printw("tonggun la");
			}
		}
		
		t_x = Snake[0].get_x();
		t_y = Snake[0].get_y();

		Key = readKey();
		switch (Key)
		{
			case up:	t_y--;	break;
			case left:	t_x--;	break;
			case right:	t_x++;	break;
			case down:	t_y++;	break;
			case stop:	stop_service();	break;
			case esc:	return false;	break;		
		}
		
		int o_x,o_y;
		vector<body>::size_type m = Snake.size()-1;
		o_x = Snake[m].get_x();
		o_y = Snake[m].get_y();

		for (; m > 0; m--)
		{
			Snake[m].set_x() = Snake[m-1].get_x();
			Snake[m].set_y() = Snake[m-1].get_y(); 
		}

		Snake[0].set_x() = t_x;
		Snake[0].set_y() = t_y;
		
		mvaddch(Snake[0].get_x(), Snake[0].get_y(), Snake[0].get_ch());
		if (Food->eat_food(Snake))
		{
			snake te(o_x,o_y,'*');
			Snake.push_back(te);
			score++;
			flag++;	
		}		
		else
		{
			mvaddch(o_x, o_y, ' ');
		}
		application::refresh();
	}	
}

